package com.movitech.mobile.ddzy.modules.syndata.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.HeadersUtils;
import com.movitech.mobile.cz.base.common.util.HttpUtil;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.modules.config.CallBackAbutmentTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.entity.SAbutmentLogs;
import com.movitech.mobile.cz.base.purchase.service.SAbutmentLogsService;
import com.movitech.mobile.cz.base.supplier.entity.SSuppliers;
import com.movitech.mobile.cz.base.supplier.service.SSuppliersService;
import com.movitech.mobile.cz.base.syndata.SynDataService;
import com.movitech.mobile.cz.base.syndata.SynSourcingDataVo;
import com.movitech.mobile.cz.base.syndata.SynSourcingDepositDataVo;
import com.movitech.mobile.cz.base.syndata.SynSupplierToMdmDataVo;
import com.movitech.mobile.ddzy.bpm.feignclient.MbsDataAuthClient;
import hk.modernland.utils.http.HttpClientUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("extSynDataService")
public class SynDataServiceImpl implements SynDataService {

    private static Logger logger = org.apache.log4j.Logger.getLogger(SynDataServiceImpl.class);


    /**
     * 更新招标状态接口地址
     */
    @Value("${syn.contract.plan.update.url}")
    private String updateContractPlanUrl;
    /**
     * 删除招标项
     */
    @Value("${syn.contract.plan.delete.url}")
    private String deleteContractPlanUrl;

    /**
     * 供应商同步到主数据接口地址
     */
    @Value("${syn.supplier.data.to.mdm.system.url}")
    private String synSupplierDataToMdmSystemUrl;
    @Value("${syn.supplier.data.to.mdm.system.usercode}")
    private String usercode;
    @Value("${syn.supplier.data.to.mdm.system.password}")
    private String passowrd;

    @Autowired
    MbsDataAuthClient mbsDataAuthClient;
    @Autowired
    SSuppliersService sSuppliersService;

    @Autowired
    @Qualifier("sAbutmentLogsService")
    private SAbutmentLogsService sAbutmentLogsService;

    @Override
    public boolean synSynSupplierData2MDM(SynSupplierToMdmDataVo synSupplierToMdmDataVo, boolean isNew) {
        LicenseUtil.INSTANCE.validate();
        CommonConstants.cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    doSynSynSupplierDataToMdm(synSupplierToMdmDataVo, isNew);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return true;
    }

    /**
     * 执行同步供应商数据到金源主数据系统
     *
     * @param synSupplierToMdmDataVo
     * @param isNew
     */

    private void doSynSynSupplierDataToMdm(SynSupplierToMdmDataVo synSupplierToMdmDataVo, boolean isNew) {
        LicenseUtil.INSTANCE.validate();
        Gson gson = new Gson();
        Map<String, Object> mapData = new HashMap<String, Object>();

        List<SynSupplierToMdmDataVo> supplierList = new ArrayList<>();
        supplierList.add(synSupplierToMdmDataVo);

        Map<String, Object> dataInfos = new HashMap<>();
        dataInfos.put("DATAINFO", supplierList);

        Map<String, Object> data = new HashMap<>();
        data.put("DATAINFOS", dataInfos);

        Map<String, Object> esb = new HashMap<>();
        esb.put("DATA", data);

        mapData.put("ESB", esb); //数据

        Map<String, String> params = new HashMap<String, String>();

        String paramJson = gson.toJson(mapData);

        SAbutmentLogs sAbutmentLogs = new SAbutmentLogs();
        sAbutmentLogs.setAbutmentType(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_10.getCode());
        sAbutmentLogs.setRelatedId(synSupplierToMdmDataVo.getSupplierId());
        sAbutmentLogs.setAbutmentContent(paramJson);
        // 返回状态，（2：失败，1：成功）
        sAbutmentLogs.setAbutmentStatus(0);
        // 0表示非实时处理或为线程异步处理，是否当前对接（0：否，1：是）
        sAbutmentLogs.setCurrentAbutmentFlag(0);
        String returnResult = "";
        try {
            Map<String, String> header = new HashMap<>();
            header.put("usercode", usercode);
            header.put("password", passowrd);
            logger.info("同步地址：" + synSupplierDataToMdmSystemUrl);
            logger.info("同步数据：" + paramJson);
            returnResult = HttpUtil.sendPostRequest(synSupplierDataToMdmSystemUrl, paramJson, header, null, null);
            logger.info("返回结果：" + returnResult);
            ESBRESULT result = gson.fromJson(returnResult, ESBRESULT.class);
            // S成功/E失败
            if ("S".equals(result.getESB().getRESULT())) {
                String supplierCode = result.getESB().getDATA().getDATAINFOS().getDATAINFO().get(0).getCODE();
                if (!StringUtils.isBlank(supplierCode)) {
                    // 1接口访问成功
                    sAbutmentLogs.setAbutmentStatus(1);
                    //获取生成的供应商编码：
                    SSuppliers suppliers = new SSuppliers();
                    suppliers.setId(synSupplierToMdmDataVo.getSupplierId());
                    suppliers.setCompanyCode(supplierCode);
                    sSuppliersService.updateById(suppliers);
                } else {
                    sAbutmentLogs.setAbutmentStatus(2);
                }
            } else {
                // 2接口访问成功，但数据未处理
                sAbutmentLogs.setAbutmentStatus(2);
            }
            sAbutmentLogs.setRemarks(returnResult);
        } catch (Exception ex) {
            // 3接口访问异常
            logger.info("数据同步失败：" + ex.getMessage());
            sAbutmentLogs.setAbutmentStatus(3);
            sAbutmentLogs.setRemarks("返回数据：" + returnResult + "异常类型：" + ex.getMessage());
        }
        sAbutmentLogsService.saveAbutmentLogs(sAbutmentLogs);
    }

    public static void main(String[] args) {

        Gson gson = new Gson();
        String a = "{\"ESB\":{\"DATA\":{\"DATAINFOS\":{\"DATAINFO\":[{\"CODE\":\"10002514\",\"CODEID\":\"10084557\",\"SYNRESULT\":\"成功\",\"SYNSTATUS\":\"0\",\"UUID\":\"DA5C39112D994D1C813E1A11734B55D6\",\"VERSION\":\"0\"}]}},\"DESC\":\"接收成功\",\"RESULT\":\"S\"}}";
        ESBRESULT ESBRESULT = gson.fromJson(a, ESBRESULT.class);
        System.out.println(ESBRESULT.getESB());
        System.out.println(ESBRESULT.getESB().getDESC());
        System.out.println(ESBRESULT.getESB().getDATA());
        System.out.println(ESBRESULT.getESB().getDATA().getDATAINFOS());
        System.out.println(ESBRESULT.getESB().getDATA().getDATAINFOS().getDATAINFO());
        System.out.println(ESBRESULT.getESB().getDATA().getDATAINFOS().getDATAINFO().get(0));
        System.out.println(ESBRESULT.getESB().getDATA().getDATAINFOS().getDATAINFO().get(0).getCODE());

    }

    /***
     * 检测旧系统中的该供应商是否已经存在
     * @param licenseNo
     * @return
     */
    @Override
    public boolean checkSupplierLicenseNo(String licenseNo) {
        boolean isOK = false;
        Gson gson = new Gson();
        try {
            if (StringUtils.isNotEmpty(licenseNo)) {
                String returnData = mbsDataAuthClient.checkLicenseNo(licenseNo);
                if (StringUtils.isNotEmpty(returnData)) {
                    RestReturnResult<String> result = gson.fromJson(returnData, new TypeToken<RestReturnResult<String>>() {
                    }.getType());
                    if (result != null) {
                        if (StringUtils.equalsIgnoreCase(result.getData(), "true")) {
                            isOK = true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isOK;
    }


    /**
     * 下发投标保证金
     *
     * @param
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public boolean invokeSourcingDeposit(List<SynSourcingDepositDataVo> synSourcingDepositDataVoList) throws RuntimeException {

        boolean flag = false;

        try {

            Gson gson = new Gson();
            Map<String, Object> mapData = new HashMap<String, Object>();
            mapData.put("class", "hk.modernland.mq.service.impl.SourcingDepositService"); //调用方法
            mapData.put("action", "insert");
            mapData.put("data", synSourcingDepositDataVoList); //数据

            Map<String, String> params = new HashMap<String, String>();
            params.put("message", gson.toJson(mapData));
            params.put("queueName", "MG.TOMBS");
            String paramJson = gson.toJson(params);

            logger.info("SynDataServiceImpl[invokeSourcingDeposit], paramJson[" + paramJson + "]");
            String returnResult = HttpClientUtils.sendPostRequest(updateContractPlanUrl, params, null, null);
            logger.info("SynDataServiceImpl[invokeSourcingDeposit], paramJson[" + paramJson + "], returnResult[" + returnResult + "]");

            //保存对接日志
            if (synSourcingDepositDataVoList != null && synSourcingDepositDataVoList.size() > 0
                    && StringUtils.equalsIgnoreCase("true", returnResult)) {

                List<SAbutmentLogs> sAbutmentLogsList = new ArrayList<SAbutmentLogs>();
                for (SynSourcingDepositDataVo synSourcingDepositDataVo : synSourcingDepositDataVoList) {
                    sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_1.getCode(), synSourcingDepositDataVo.getSdServiceUuid(), JSONArray.toJSONString(synSourcingDepositDataVoList), 1, 1);
                }
            } else {
                throw new RuntimeException("对接失败");
            }

            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

        return flag;
    }

    /***
     * 下发招标项状态控制
     * @param synSourcingDataVo
     * @return
     */
    @Override
    public boolean changeSourcingStatus(SynSourcingDataVo synSourcingDataVo) throws RuntimeException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        final String token = HeadersUtils.getHeadByKey(request, "token");
        System.out.println("----token===" + token);
        CommonConstants.cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    changeSourcingStatusDone(synSourcingDataVo, token);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return true;
    }

    /***
     * 下发招标项状态控制
     * @param synSourcingDataVo
     * @return
     */
    private boolean changeSourcingStatusDone(SynSourcingDataVo synSourcingDataVo, String token) throws RuntimeException {
        boolean flag = false;
        if (synSourcingDataVo == null || (synSourcingDataVo != null && StringUtils.isEmpty(synSourcingDataVo.getSrId()))) {
            flag = true;
        } else {
            Map<String, String> params = new HashMap<String, String>();
            params.put("uuid", synSourcingDataVo.getSrId());
            params.put("srStatus", synSourcingDataVo.getSrStatus());
            if ("1".equals(synSourcingDataVo.getSrStatus())) {
                params.put("status", "3");//招标进行中
            } else {
                params.put("status", "2");//成本系统：2：合约规划已推送
            }
            Gson gson = new Gson();
            String paramJson = gson.toJson(params);
            Map<String, String> header = new HashMap<>();
            header.put("token", token);
            try {
                logger.info("SynDataServiceImpl[changeSourcingStatus], paramJson[" + paramJson + "]");
                String returnResult = HttpUtil.sendPostRequest(updateContractPlanUrl, paramJson, header, null, null);
                logger.info("SynDataServiceImpl[changeSourcingStatus],url[" + updateContractPlanUrl + "], paramJson[" + paramJson + "], returnResult[" + returnResult + "]");

                //保存对接日志
                JSONObject resultObj = JSONObject.parseObject(returnResult);
                if (StringUtils.equalsIgnoreCase(resultObj.getString("code"), "1")) {
                    sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), synSourcingDataVo.getSrId(), JSONArray.toJSONString(params), returnResult, 1, 1);
                } else {
                    sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), synSourcingDataVo.getSrId(), JSONArray.toJSONString(params), returnResult, 0, 1);
                }
                flag = true;
            } catch (Exception e) {
                //保存对接日志
                sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), synSourcingDataVo.getSrId(), JSONArray.toJSONString(params), e.getMessage(), 0, 1);
            }
        }

        return flag;
    }

    /**
     * 查询招标项调度状态
     *
     * @param srCode
     * @return
     */
    @Override
    public String querySourcingStatus(String srCode) {
        String res = null;
        String status = "false";
        try {
            res = mbsDataAuthClient.querySourcingStatus(srCode);
            if (StringUtils.isNotEmpty(res)) {
                JSONObject jsonObject = JSONObject.parseObject(res);
                if (jsonObject.getInteger("code") == 1) {
                    status = jsonObject.getJSONArray("data").getJSONObject(0).getString("status");
                }
            }
        } catch (Exception e) {
            System.out.println("===========querySourcingStatus===e======" + e);
            e.printStackTrace();
        }
        return status;
    }

    @Override
    public boolean deletemergeContract(String contractId, String contractDetailIdId) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        final String token = HeadersUtils.getHeadByKey(request, "token");
        System.out.println("----token===" + token);

        Map<String, String> params = new HashMap<String, String>();
//        params.put("uuid", contractId);
//        params.put("targetCostDataUuids", contractDetailIdId);
        Gson gson = new Gson();
        Map<String, String> header = new HashMap<>();
        header.put("Token", token);
        StringBuilder sb = new StringBuilder(deleteContractPlanUrl);
        sb.append("?").append("uuid=").append(contractId).append("&targetCostDataUuids=").append(contractDetailIdId);
        params.put("url",sb.toString());
        params.put("Token",token);
        String paramJson = gson.toJson(params);
        try {
            logger.info("SynDataServiceImpl[deletemergeContract], paramJson[" + paramJson + "]");
            String returnResult = HttpUtil.sendPostRequest(sb.toString(), paramJson, header, null, null);
            logger.info("SynDataServiceImpl[deletemergeContract],url[" + sb.toString() + "], paramJson[" + paramJson + "], returnResult[" + returnResult + "]");

            //保存对接日志
            JSONObject resultObj = JSONObject.parseObject(returnResult);
            if (StringUtils.equalsIgnoreCase(resultObj.getString("code"), "1")) {
                sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), contractId, JSONArray.toJSONString(params), returnResult, 1, 1);
                return true;
            } else {
                logger.info("url[" + sb.toString() + "]接口调用失败");
                sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), contractId, JSONArray.toJSONString(params), returnResult, 0, 1);
                return false;
            }
        } catch (Exception e) {
            //保存对接日志
            logger.info("url[" + sb.toString() + "]接口调用失败：" + e.getMessage());
            sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_9.getCode(), contractId, JSONArray.toJSONString(params), e.getMessage(), 0, 1);
        }
        return false;
    }
}
